package cn.matrix42.potoo.jdbc.dialect.mysql;

import cn.matrix42.potoo.jdbc.dialect.AbstractDialect;

import java.util.Arrays;
import java.util.Optional;
import java.util.stream.Collectors;

public class MySQLDialect extends AbstractDialect {

    private static final String DRIVER = "com.mysql.jdbc.Driver";
    private static final String URL_PATTERN = "jdbc:mysql://%s:%d/%s";

    @Override
    public String dialectName() {
        return "MySQL";
    }

    @Override
    public String getLimitClause(long limit) {
        return "LIMIT " + limit;
    }

    @Override
    public String quoteIdentifier(String identifier) {
        return "`" + identifier + "`";
    }

    @Override
    public Optional<String> getUpsertStatement(String tableName, String[] fieldNames, String[] uniqueKeyFields) {
        String updateClause =
            Arrays.stream(fieldNames)
                .map(f -> quoteIdentifier(f) + "=VALUES(" + quoteIdentifier(f) + ")")
                .collect(Collectors.joining(", "));
        return Optional.of(
            getInsertIntoStatement(tableName, fieldNames)
                + " ON DUPLICATE KEY UPDATE "
                + updateClause);
    }

    @Override
    public String getDriver() {
        return DRIVER;
    }

    @Override
    public String getUrlPattern() {
        return URL_PATTERN;
    }
}
